const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const copyWebpackPlugin = require('copy-webpack-plugin');
const fs = require('fs');

const plugins = (dev, dir)=> {
    var result = [
        new HtmlWebpackPlugin({
            template: "./src/index.html",
            inject: "head",
            scriptLoading: "blocking"
        })
    ];
    return result;
}

function delDir(path){
    let files = [];
    if(fs.existsSync(path)){
        files = fs.readdirSync(path);
        files.forEach((file, index) => {
            let curPath = path + "/" + file;
            if(fs.statSync(curPath).isDirectory()){
                delDir(curPath); //递归删除文件夹
            } else {
                fs.unlinkSync(curPath); //删除文件
            }
        });
        fs.rmdirSync(path);
    }
}

module.exports = (args, envs) => {
    var mode = envs.mode ? envs.mode : 'development';
    var prod = mode == 'production';
    var dev = mode == 'development';
    var dir = path.resolve(__dirname, (prod ? 'dist' : 'dev'));
    delDir(dir);
    return [{
        mode: mode,
        entry: {
            'sneakxy-validator': {
                 library: {
                    name: 'SneakxyValidator',
                    type: 'umd',
                    export: 'default'
                },
                import: './src/index.js'
            },
            "locale/zh-CN": './src/loader/zh-CN.js',
            "locale/en-US": './src/loader/en-US.js'
        },
        output: {
            filename: '[name].min.js',
            path: dir
        },
        devtool: false,
        plugins: plugins(dev, dir),
        performance: { hints: false }
    }];
}